package leetcode

import kotlinetc.println

//https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/
/**

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.

Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d]+101[e]+101[e] to the sum.  Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let" , and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Note:

0 < s1.length, s2.length <= 1000.
All elements of each string will have an ASCII value in [97, 122].
Accepted  22,740  Submissions 41,151
 */

fun main(args: Array<String>) {

    //"delete"
    //"leet"
    //eet  let

//    println('t'.toInt())
//    println('e'.toInt())
//    println('l'.toInt())
//    println('d'.toInt())

    minimumDeleteSum("delete", "leet").println()
}


//DP
/**
这题是 LCS 的变种，LCS 中的dp是保存最长公共子序列的长度，但是这里需要保存 delete 的 ascii 值之和

ai == bj   那么 r = ai-1bj-1
ai ≠ bj 那么 r = Max(ai-1bj+ ai,aibj-1+ bj)

 */
fun minimumDeleteSum(s1: String, s2: String): Int {

    val lena = s1.length
    val lenb = s2.length

    val dp = Array(lena + 1, { Array(lenb + 1, { 0 }) })


    //这里需要特别注意，初始化的时候是累加前面的值，和 lcs 性质不一样
    for (i in 0..lena)
        dp[i][0] = if (i == 0) 0 else s1[i - 1].toInt() + dp[i - 1][0]

    for (i in 1..lenb)
        dp[0][i] = s2[i - 1].toInt() + dp[0][i - 1]


    for (i in 1..lena)
        for (j in 1..lenb) {
            if (s1[i - 1] == s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1]
            else
                dp[i][j] = Math.min(dp[i - 1][j] + s1[i - 1].toInt(), dp[i][j - 1] + s2[j - 1].toInt())
        }

    return dp[lena][lenb]
}